<template>
    <view class="edit-address-container">
        <view class="form-container">
            <!-- 姓名 -->
            <view class="form-item">
                <text class="form-label">姓名</text>
                <uv-input v-model="formData.address_name" placeholder="请输入姓名" :border="'none'"
                    customStyle="text-align: right; color: #666;" />
            </view>

            <!-- 手机号 -->
            <view class="form-item">
                <text class="form-label">手机号</text>
                <uv-input v-model="formData.address_mobile" placeholder="请输入手机号" :border="'none'"
                    customStyle="text-align: right; color: #666;" maxlength="11" />
            </view>

            <!-- 省/直辖市 -->
            <view class="form-item" @click="showProvincePicker">
                <text class="form-label">省/直辖市</text>
                <view class="form-value">
                    <text class="value-text">{{ formData.province || '请选择省份' }}</text>
                    <uv-icon name="arrow-right" color="#ccc" size="16" />
                </view>
            </view>

            <!-- 市/区 -->
            <view class="form-item" @click="showCityPicker">
                <text class="form-label">市/区</text>
                <view class="form-value">
                    <text class="value-text">{{ formData.city || '请选择城市' }}</text>
                    <uv-icon name="arrow-right" color="#ccc" size="16" />
                </view>
            </view>

            <!-- 县/镇 -->
            <view class="form-item" @click="showRegionPicker">
                <text class="form-label">县/镇</text>
                <view class="form-value">
                    <text class="value-text">{{ formData.region || '请选择区县' }}</text>
                    <uv-icon name="arrow-right" color="#ccc" size="16" />
                </view>
            </view>

            <!-- 详细地址 -->
            <view class="form-item form-item-textarea">
                <text class="form-label">详细地址</text>
                <uv-textarea v-model="formData.address_detail" placeholder="请输入详细地址" maxlength="200"
                    customStyle="margin-top: 16rpx;width:100%" />
            </view>

            <!-- 设为默认地址 -->
            <view class="form-item">
                <text class="form-label">设为默认地址</text>
                <uv-switch v-model="formData.is_default" size="24" activeColor="#FF6B35" />
            </view>
        </view>

        <!-- 保存按钮 -->
        <view class="save-btn-container">
            <uv-button text="保存"
                customStyle="border-radius: 24rpx; height: 88rpx; background-color: #FF6B35; color: #fff;"
                @click="saveAddress" />
        </view>

        <!-- 省份选择器 -->
        <uv-action-sheet ref="provincePicker" :actions="provinceActions" title="选择省份" @select="onProvinceSelect" />

        <!-- 城市选择器 -->
        <uv-action-sheet ref="cityPicker" :actions="cityActions" title="选择城市" @select="onCitySelect" />

        <!-- 区县选择器 -->
        <uv-action-sheet ref="regionPicker" :actions="regionActions" title="选择区县" @select="onRegionSelect" />
    </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useRequest } from '@/api'
const { GET_ADRESS_DETAIL, SAVE_ADDRESS, GET_ADRESS_AREA, ADD_ADDRESS } = useRequest()
import { UserInfoManager } from '@/utils/userInfo'

// 页面参数
const addressId = ref('')
// 统一通过 onLoad 获取路由参数，兼容 APP/H5/小程序
onLoad((options: Record<string, any>) => {
    const id = options?.id
    if (id) {
        try {
            addressId.value = decodeURIComponent(String(id))
        } catch {
            addressId.value = String(id)
        }
    }
})

// 表单数据
const formData = reactive({
    id: '',
    address_name: '',
    address_mobile: '',
    province: '',
    province_id: '',
    city: '',
    city_id: '',
    region: '',
    region_id: '',
    address_detail: '',
    is_default: false
})

const loading = ref(false)

// 选择器引用
const provincePicker = ref()
const cityPicker = ref()
const regionPicker = ref()


// 当前选中的省市区ID
const selectedProvinceId = ref('')
const selectedCityId = ref('')

// Action Sheet 显示状态（已移除，改为使用ref控制）

// Action Sheet 数据
const provinceActions = ref([])
const cityActions = ref([])
const regionActions = ref([])

// 显示省份选择器
const showProvincePicker = () => {
    provincePicker.value?.open()
}

// 显示城市选择器
const showCityPicker = () => {
    if (!formData.province) {
        uni.showToast({
            title: '请先选择省份',
            icon: 'none'
        })
        return
    }
    cityPicker.value?.open()
}

// 显示区县选择器
const showRegionPicker = () => {
    if (!formData.city) {
        uni.showToast({
            title: '请先选择城市',
            icon: 'none'
        })
        return
    }
    regionPicker.value?.open()
}


// 省份选择确认
const onProvinceSelect = (item: any) => {
    formData.province = item.name
    formData.province_id = item.value.toString()
    formData.city = ''
    formData.city_id = ''
    formData.region = ''
    formData.region_id = ''

    selectedProvinceId.value = item.value.toString()
    selectedCityId.value = ''

    // 获取城市列表
    getCityList()
}

// 城市选择确认
const onCitySelect = (item: any) => {
    formData.city = item.name
    formData.city_id = item.value.toString()
    formData.region = ''
    formData.region_id = ''

    selectedCityId.value = item.value.toString()

    // 获取区县列表
    getRegionList()
}

// 区县选择确认
const onRegionSelect = (item: any) => {
    formData.region = item.name
    formData.region_id = item.value.toString()
}

// 获取地址详情
const getAddressDetail = async () => {
    if (!addressId.value) return

    loading.value = true
    try {
        const params = {
            id: addressId.value,
            isdriver: UserInfoManager.lastrole()
        }

        const res = await GET_ADRESS_DETAIL(params)
        if (res.code === 1 && res.data) {
            Object.assign(formData, {
                id: res.data.id || '',
                address_name: res.data.address_name || '',
                address_mobile: res.data.address_mobile || '',
                province: res.data.province || '',
                province_id: res.data.province_id || '',
                city: res.data.city || '',
                city_id: res.data.city_id || '',
                region: res.data.region || '',
                region_id: res.data.region_id || '',
                address_detail: res.data.address_detail || '',
                is_default: res.data.is_default === 'Y'
            })

            // 设置选中的省市区ID，用于后续获取城市和区县列表
            selectedProvinceId.value = res.data.province_id || ''
            selectedCityId.value = res.data.city_id || ''

            // 如果有省份ID，获取城市列表
            if (selectedProvinceId.value) {
                getCityList()
            }

            // 如果有城市ID，获取区县列表
            if (selectedCityId.value) {
                getRegionList()
            }
        } else {
            uni.showToast({
                title: res.msg || '获取地址详情失败',
                icon: 'none'
            })
        }
    } catch (error) {
        console.error('获取地址详情失败:', error)
        uni.showToast({
            title: '获取地址详情失败',
            icon: 'none'
        })
    } finally {
        loading.value = false
    }
}

// 保存地址
const saveAddress = async () => {
    // 表单验证
    if (!formData.address_name.trim()) {
        uni.showToast({
            title: '请输入姓名',
            icon: 'none'
        })
        return
    }

    if (!formData.address_mobile.trim()) {
        uni.showToast({
            title: '请输入手机号',
            icon: 'none'
        })
        return
    }

    // 手机号格式验证
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(formData.address_mobile)) {
        uni.showToast({
            title: '请输入正确的手机号',
            icon: 'none'
        })
        return
    }

    if (!formData.province) {
        uni.showToast({
            title: '请选择省份',
            icon: 'none'
        })
        return
    }

    if (!formData.city) {
        uni.showToast({
            title: '请选择城市',
            icon: 'none'
        })
        return
    }

    if (!formData.region) {
        uni.showToast({
            title: '请选择区县',
            icon: 'none'
        })
        return
    }

    if (!formData.address_detail.trim()) {
        uni.showToast({
            title: '请输入详细地址',
            icon: 'none'
        })
        return
    }

    uni.showLoading({
        title: '保存中...'
    })

    try {
        const params: any = {
            ...formData,
            is_default: formData.is_default ? 'Y' : 'N',
            isdriver: UserInfoManager.lastrole()
        }
        // 新增时不传 id
        if (!addressId.value) {
            delete params.id
        }

        const res = await (addressId.value ? SAVE_ADDRESS(params) : ADD_ADDRESS(params))
        if (res.code === 1) {
            uni.showToast({
                title: '保存成功',
                icon: 'success'
            })

            // 通知地址列表页面刷新
            uni.$emit('refreshAddressList')

            setTimeout(() => {
                uni.navigateBack()
            }, 500)
        } else {
            uni.showToast({
                title: res.msg || '保存失败',
                icon: 'none'
            })
        }
    } catch (error) {
        console.error('保存地址失败:', error)
        uni.showToast({
            title: '保存失败',
            icon: 'none'
        })
    } finally {
        uni.hideLoading()
    }
}

// 获取省份列表
const getProviceList = async () => {
    const params = {
        isdriver: UserInfoManager.lastrole()
    }
    const res = await GET_ADRESS_AREA(params)
    if (res.code === 1) {
        provinceActions.value = res.data
    }
}

// 获取城市列表
const getCityList = async () => {
    if (!selectedProvinceId.value) return

    const params = {
        isdriver: UserInfoManager.lastrole(),
        province: selectedProvinceId.value
    }
    const res = await GET_ADRESS_AREA(params)
    if (res.code === 1) {
        cityActions.value = res.data
    }
}

// 获取区县列表
const getRegionList = async () => {
    if (!selectedCityId.value) return

    const params = {
        isdriver: UserInfoManager.lastrole(),
        city: selectedCityId.value,
        province: selectedProvinceId.value
    }
    const res = await GET_ADRESS_AREA(params)

    if (res.code === 1) {
        regionActions.value = res.data
    }
}
onMounted(() => {
    getProviceList()
    if (addressId.value) {
        getAddressDetail()
    } else {
        // 如果是新增地址，初始化ID字段
        selectedProvinceId.value = ''
        selectedCityId.value = ''
    }
})
</script>

<style lang="scss" scoped>
.edit-address-container {
    min-height: 100vh;
    background: #f6f7f9;
    padding-bottom: 120rpx;
}

.form-container {
    background: #fff;
    margin: 20rpx;
    border-radius: 16rpx;
    overflow: hidden;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
}

.form-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 32rpx 24rpx;
    border-bottom: 1rpx solid #f8f8f8;

    &:last-child {
        border-bottom: none;
    }

    &.form-item-textarea {
        flex-direction: column;
        align-items: flex-start;
        padding-bottom: 24rpx;
    }
}

.form-label {
    font-size: 30rpx;
    color: #333;
    font-weight: 500;
    min-width: 160rpx;
}

.form-value {
    display: flex;
    align-items: center;
    gap: 12rpx;
}

.value-text {
    font-size: 30rpx;
    color: #666;
}

.save-btn-container {
    padding: 40rpx 24rpx;
}

/* 响应式调整 */
@media (max-width: 750rpx) {
    .form-item {
        padding: 28rpx 20rpx;
    }

    .form-label {
        font-size: 28rpx;
        min-width: 140rpx;
    }

    .value-text {
        font-size: 28rpx;
    }
}
</style>
